﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DDD从零起步.Controllers
{
    using Domain.Core;
    using Domain.Entities;
    using Infrastructure;
    using Domain.Core.Extensions;
    public class ZTreeController : Controller
    {
        IRepository<Category> irepository;
        public ZTreeController()
        {
            irepository = new BackgroundRepository<Category>();
        }

        public ActionResult Index()
        {
            var list = irepository.GetEntities();
            ViewBag.List = list.OrderByNewId().Take(5).ToList();//只取5条
            return View();
        }

        #region 对节点的操作
        /// <summary>
        /// 得到一级子节点
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string AsyncGetNodes(int? id)
        {
            var model = irepository.GetEntities()
                                   .Where(i => i.ParentID == id)
                                   .OrderBy(i => i.Sortable);

            return model.ToJson();
        }
        /// <summary>
        /// 添加节点
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public string AsyncAddNodes(int id, string name, int pid)
        {
            try
            {
                //得到父对象，但设置它的isParent属性
                irepository.Modify(i => new Category
                  {
                      ID = pid,
                      IsParent = true,
                  });

                var entity = new Category
                {
                    Name = name,
                    ParentID = pid,
                    CreateDate = DateTime.Now,
                    Level = 1,
                    IsParent = false,
                };
                irepository.Add(entity);

                return entity.ID.ToString();
            }
            catch (Exception ex)
            {

                return ex.Message;
            }

        }
        /// <summary>
        /// 编辑节点（重命名）
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public string AsyncEditNodes(int id, string name)
        {
            try
            {
                irepository.Modify(i => new Category
                {
                    ID = id,
                    Name = name,
                });
                return "操作成功";
            }
            catch (Exception ex)
            {

                return ex.Message;
            }
        }
        /// <summary>
        /// 删除节点
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string AsyncDelNodes(int id)
        {
            try
            {
                irepository.Remove(irepository.GetEntity(i => i.ID == id));
                return "操作成功";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// 拖拽节点
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid"></param>
        /// <param name="sortable"></param>
        /// <returns></returns>
        public string AsyncDragNodes(
            int id,
            int pid,
            string name,
            string moveType,
            bool isCopy)
        {
            try
            {
                var parent = irepository.GetEntity(i => i.ID == pid);
                var parentSons = irepository.GetEntities(i => i.ParentID == pid);
                var current = irepository.GetEntity(i => i.ID == id);
                if (moveType == "inner")
                    parent.isParent = true;
                else if (parentSons == null || parentSons.Count() == 0)
                    parent.isParent = false;
                if (isCopy)//复制，前台目前不能实现
                {
                    List<Category> sons = irepository.GetEntities(i => i.ParentID == id).ToList();

                    bool isParent = false;
                    if (sons != null && sons.Count > 0)
                        isParent = true;
                    var entity = new Category
                    {
                        ParentID = pid,
                        Name = name,
                        CreateDate = DateTime.Now,
                        IsParent = isParent,
                    };
                    irepository.Add(entity);
                    if (isParent)
                    {
                        sons.ForEach(i =>
                        {
                            i.ParentID = entity.id;
                            irepository.Add(i);
                        });
                    }

                }
                else
                {
                    if (moveType == "inner")
                    {
                        current.ParentID = pid;
                        irepository.Modify(current);
                    }
                    else
                    {
                        current.ParentID = parent.ParentID;//同级移动时，与目标节点父ID相同
                        current.Sortable = moveType == "next"
                            ? parent.Sortable + 1
                            : parent.Sortable - 1;
                        irepository.Modify(current);
                    }
                }
                irepository.Modify(parent);
                return "操作成功";
            }
            catch (Exception ex)
            {

                return ex.Message;
            }
        }
        #endregion


    }
}
